<template>
    <div class="app-container">
        <el-card class="box-card" shadow="always" v-show="showSearch">
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
                <el-form-item label="客户名称" prop="clientId">
                    <el-select v-model="queryParams.clientId" filterable clearable remote reserve-keyword
                        placeholder="请选择客户" :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')"
                        :loading="loading" @change="handleQuery">
                        <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker style="width:240px" placeholder="选择方案日期" v-model="dateRange"
                        value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期"
                        end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="报价单号" prop="quotationCode">
                    <el-input v-model="queryParams.quotationCode" placeholder="报价单号" clearable
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="状态" prop="quotationStatus">
                    <el-select v-model="queryParams.quotationStatus" clearable reserve-keyword placeholder="报价状态"
                        @change="handleQuery">
                        <el-option v-for="item in quote_status" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="报价人" prop="quotationUserId">
                    <el-select v-model="queryParams.quotationUserId" filterable clearable remote reserve-keyword
                        placeholder="请选择报价人" :loading="loading" @change="handleQuery">
                        <el-option v-for="item in userList" :key="item.value" :label="item.nickName"
                            :value="item.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系人" prop="quotationName">
                    <el-input v-model="queryParams.quotationName" placeholder="请输入联系人" clearable
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="单据备注" prop="remark">
                    <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="box-card" shadow="always" :body-style="{ padding: '20px' }">
            <template #header>
                <div>
                    <el-row :gutter="10" class="mb8">

                        <el-button type="primary" @click="handleAdd" v-hasPermi="['order:quotation:add']">添加报价单
                        </el-button>
                        <el-radio-group v-model="queryParams.quotationStatus" is-button class="ml10"
                            @change="handleQuery">
                            <el-radio-button label="">全部报价</el-radio-button>
                            <el-radio-button v-for="item in quote_status" :key="item.value" :label="item.value">
                                {{ item.label }}
                            </el-radio-button>
                        </el-radio-group>
                        <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                    </el-row>
                </div>
            </template>
            <!-- card body -->
            <!-- <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary"  icon="el-icon-plus"  @click="handleAdd"
                        v-hasPermi="['plan:order:add']">添加报价单
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger"  icon="el-icon-delete"  :disabled="multiple"
                        @click="handleDelete" v-hasPermi="['plan:order:remove']">删除
                    </el-button>
                </el-col>
                <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row> -->

            <el-table border show-summary :summary-method="getSummaries" v-loading="loading" :data="dataSource"
                @selection-change="handleSelectionChange" @row-dblclick="dbclick">
                <el-table-column type="selection" width="60" align="center" :selectable="selectHandle" />
                <el-table-column label="#" type="index"> </el-table-column>
                <el-table-column label="报价单号" align="center" prop="quotationCode" />
                <el-table-column label="日期" align="center" prop="quotationTime" width="220" />
                <el-table-column label="最近跟单时间" align="center" prop="quotationProgressTime" width="220" />
                <el-table-column label="客户名称" align="center">
                    <template #default="scope">
                        {{ scope.row.jzgSupplierVo && scope.row.jzgSupplierVo.supplierName || '' }}
                    </template>
                </el-table-column>
                <el-table-column label="报价人" align="center" prop="quotationUserName" />
                <el-table-column label="联系人" align="center" prop="quotationName" />
                <el-table-column label="数量" align="center" prop="goodsNo" />
                <el-table-column label="报价金额" align="center" prop="clueSourcepplyPrice" />
                <el-table-column label="报价状态" align="center" prop="quotationStatus">
                    <template #default="scope">
                        <el-tag :type="getType(scope.row.quotationStatus)" size="normal" effect="dark">
                            {{ selectDictLabel(quote_status, scope.row.quotationStatus) }}

                        </el-tag>
                        <!-- 
                        <el-icon color="#409eff" style="cursor: pointer;margin-left: 5px;" @click="handleStatus(scope.row)">
                            <Edit />
                        </el-icon> -->

                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="操作" align="center" prop="orderStatus" width="250">
                    <template #default="scope">
                        <el-button type="text" @click="handleTracking(scope.row)">报价跟进</el-button>
                        <el-button type="text" @click="downloadPPT(scope.row)">下载PPT</el-button>
                        <el-button type="text" @click="shareIm(scope.row)">分享好友</el-button>
                        <el-button type="text" @click="handleEdit(scope.row)"
                            v-hasPermi="['order:quotation:edit']">编辑</el-button>
                        <el-button text type="danger " @click="handleDelete(scope.row.id)"
                            v-hasPermi="['order:quotation:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page.sync="queryParams.pageNum"
                v-model:limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <addForm ref="modelForm" @ok="handleQuery"></addForm>
        <statusForm ref="statusForm"></statusForm>
        <trackingForm ref="trackingForm" @ok="handleQuery"></trackingForm>
        <selectTemplate ref="selectTemplate" @ok="selectOk"></selectTemplate>
        <shareForm ref="shareForm"></shareForm>
    </div>
</template>

<script>
import addForm from './modules/addForm.vue';
import statusForm from './modules/statusForm.vue';
import trackingForm from './modules/trackingForm.vue';
import shareForm from './modules/shareIm.vue';
import listMixin from '@/mixins/listMixin';
import selectTemplate from '../template/modules/selectTemplate.vue';
import useExport from '@/components/PPTist/hooks/useExport'
import { randomUUID } from '@/utils/util'
import { getQuotation } from '@/api/goods/quotation';
const { exportPPTX, exporting } = useExport()
export default {
    name: "quotationTracking",
    dicts: ["inventory_status", "counting_method"],
    components: {
        addForm, statusForm,
        selectTemplate, trackingForm,
        shareForm
    },
    mixins: [listMixin],
    data() {
        return {
            showSearch: true, // Whether to show the search form
            queryParams: { // Query parameters for the table
                pageNum: 1, // Current page number
                pageSize: 10, // Number of records per page
                quotationStatus: '0', // Quotation number
            },
            dateRange: [], // Date range for the created time
            loading: false, // Loading state of the table
            dataSource: [], // Data for the table
            total: 0, // Total number of records
            multiple: false, // Whether multiple rows are selected
            quote_status: [], // Quote status
            supplierOptions: [],//客户
            quotationSchemeOptions: [],//方案
            currentRow: {}, // Current row data
            urls: {
                list: '/order/quotation/list',
                delete: '/order/quotation',
            }
        };
    },
    mounted() {
        this.getDicts(['quote_status']);
        this.getSupplierAllList(1);
        this.listSysUser()
    },
    methods: {
        getQueryParams() {
            let params = Object.assign({}, this.queryParams);
            params.params = { ...this.params };
            if (this.dateRange && this.dateRange.length) {
                params.params['beginQuotationTime'] = this.dateRange[0];
                params.params['endQuotationTime'] = this.dateRange[1];
            }
            return params;
        },
        remoteMethod(query, listKey, key) {
            const optionKey = listKey + 'Options';
            if (query !== '') {

                this[optionKey] = this[listKey + 'List'].filter(item => {
                    return item[key].toLowerCase()
                        .indexOf(query.toLowerCase()) > -1;
                });
            } else {
                this[optionKey] = this[listKey + 'List'];
            }

        },
        handleStatus(row) {
            console.log('666 :>> ', 666);
            this.$refs.statusForm.edit(row);
        },
        downloadPPT(row) {
            this.currentRow = row
            this.$refs.selectTemplate.show();
        },
        async selectOk(row) {
            const res = await getQuotation(this.currentRow.id)

            const data = {
                goodsName: '商品名称',
                goodsSku: 'SKU',
                itemNo: '货号',
                primarilyImg: '商品默认图片',
                packImg: '商品主图',
                auxiliaryImg: '商品副图',
                goodsUnit: '商品单位',
                goodsSize: '商品尺寸',
                costPrice: '成本价',
                wholesalePrice: '批发价',
                upsetPrice: '最低售价',
                retailPrice: '零售价',
                purchasePrice: '一件代发采购价',
                salePrice: '一件代发销售价',
                supplyMode: '供货方式',
            }
            res.data.quotationItemVoList = res.data.quotationItemVoList.map(v => (v.jzgGoodsVo = data, v))
            let slides = this.resetSelides(row, res.data)
            exportPPTX(slides, false, false, row.pptName)
        },
        // 计算slides
        /**
         * 
         * @param {*} templateInfo 模板信息
         * @param {*} materialInfo 商品
         */
        resetSelides(templateInfo, materialInfo) {
            // 重置slides
            let newSlides = []
            let defaultSlides = JSON.parse(templateInfo.remark)
            console.log('defaultSlides :>> ', defaultSlides);
            defaultSlides.forEach((slide) => {
                if (!slide.isDynamic) {
                    newSlides.push(slide)
                } else {
                    (materialInfo.quotationItemVoList || []).forEach(val => {
                        newSlides.push({
                            ...slide,
                            id: slide.id + randomUUID(),
                            elements: slide.elements.map((element) => {
                                if (element.keyStr) {
                                    let pattern = />([^<]+)</g
                                    let bodyString = element.content.replace(pattern, `>${val.jzgGoodsVo[element.keyStr]}<`)
                                    return {
                                        ...element,
                                        content: bodyString
                                    }
                                }
                                return element
                            })
                        })
                    });
                }
            })
            return newSlides
        },
        getType(status) {
            switch (status) {
                case '0':
                    return 'primary';
                case '1':
                    return 'success';
                case '2':
                    return 'danger';
                default:
                    return 'info';
            }
        },
        getSummaries(param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计'
                    return
                }
                const values = data.map((item) => Number(item[column.property]))
                const keyArr = ['applyPrice', 'number']
                if (keyArr.includes(column.property)) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr)
                        if (!Number.isNaN(value)) {
                            return prev + curr
                        } else {
                            return prev
                        }
                    }, 0)
                } else {
                    sums[index] = '-'
                }
            })

            return sums
        },
        handleTracking(row) {
            this.$refs.trackingForm.edit(row);
        },
        shareIm(row) {
            this.$refs.shareForm.pick(row);
        },
        /**
         * @重置查询条件
         */
        resetQuery() {
            this.queryParams = {//查询条件
                pageNum: 1,
                pageSize: 10
            }
            this.dateRange = []
            this.getList()
        },
    },
};
</script>
<style type="text/css" scoped>
.box-card {
    margin-bottom: 10px;
}
</style>